package com.wakala.employment.fragment.other;

import static com.kongzue.dialogx.dialogs.PopTip.tip;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hjq.toast.Toaster;
import com.leaf.library.StatusBarUtil;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.FlowTagSimpleAdapter;
import com.wakala.employment.adapter.jobCategory.RvListener;
import com.wakala.employment.adapter.jobCategory.TagSelectListener;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentCitySelectBinding;
import com.wakala.employment.databinding.FragmentRegionSelectBinding;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.SystemCityTreeVo;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.tip.ToastUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import co.lujun.androidtagview.TagContainerLayout;
import co.lujun.androidtagview.TagView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RegionSelectFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class RegionSelectFragment extends BaseFragment<FragmentRegionSelectBinding> implements View.OnClickListener {

    private String TAG = "CitySelectFragment";

    private RecyclerView rvSort;
    private RecyclerView rvDetail;
    private CommonAdapter<SystemCityTreeVo> rvSortAdapter;
    private CommonAdapter<SystemCityTreeVo> rvDetailAdapter;
    private List<SystemCityTreeVo> rvSortList = new ArrayList<>();
    private List<SystemCityTreeVo> rvDetailList = new ArrayList<>();
    ;
    private int rvSortCheckedPosition = 0;
    private int rvDetailCheckedPosition = 0;

    private SystemCityTreeVo leftCategoryBean = null;
    private SystemCityTreeVo rightCategoryBean = null;

    private boolean isMoved;
    private int targetPosition;//点击左边某一个具体的item的位置

    private LinearLayoutManager mLinearLayoutManager;
    private LinearLayoutManager mDetailLinearLayoutManager;


    //tagView布局管理器
    TagContainerLayout mTagContainerLayout;
    private ArrayList<String> tagLayoutTags = new ArrayList<>();
    private int resultSize = 5;

    private ArrayList<SystemCityTreeVo> selectedJobList = new ArrayList<>();
    private Map<String, FlowTagLayout> flowTagLayoutMap = new HashMap<>();

    @NonNull
    @Override
    protected FragmentRegionSelectBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentRegionSelectBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("城市选择");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(requireActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        requireActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    @Override
    protected void initViews() {
        //设置清除按钮 默认魏 disabled状态，当选择的工种类型列表不为空时才可以点击，进行清除操作，
        //当工种类型选择列表为空时设置清除按钮魏 disabled状态。
        binding.btnClearOptions.setEnabled(false);
        binding.btnClearOptions.setOnClickListener(this);
        binding.btnConfirmOptions.setOnClickListener(this);
        binding.flKindShow.setVisibility(View.GONE);
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        //初始化左侧列表数据
        rvSort = binding.rvSort;
        rvSort.setLayoutManager(mLinearLayoutManager);
        rvDetail = binding.rvDetail;
        //
        DividerItemDecoration decoration = new DividerItemDecoration(requireContext(),
                DividerItemDecoration.VERTICAL);
        rvSort.addItemDecoration(decoration);
        rvSortAdapter = new CommonAdapter<SystemCityTreeVo>(getContext(), R.layout.item_region_category_sort_list, rvSortList) {
            @Override
            protected void convert(ViewHolder holder, SystemCityTreeVo systemCityTreeVo, int position) {
                View mView = holder.itemView;
                View mTvTag = holder.getView(R.id.tv_sort_tag);
                TextView tvName = holder.getView(R.id.tv_sort);
                tvName.setText(systemCityTreeVo.getName());
                //
                if (position == rvSortCheckedPosition) {
                    mView.setBackgroundColor(Color.parseColor("#f3f3f3"));
                    tvName.setTextColor(Color.parseColor("#0068cf"));
                    mTvTag.setBackgroundColor(Color.parseColor("#0068cf"));
                } else {
                    mView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    tvName.setTextColor(Color.parseColor("#1e1d1d"));
                    mTvTag.setBackgroundColor(Color.parseColor("#FFFFFF"));
                }

            }
        };
        rvSortAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                rvSortCheckedPosition = i;
                rvSortAdapter.notifyDataSetChanged();
                new LeftRvListener().onItemClick(view.getId(), i);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
        rvSort.setAdapter(rvSortAdapter);
        //
        mDetailLinearLayoutManager = new LinearLayoutManager(getContext());
        rvDetail.setLayoutManager(mDetailLinearLayoutManager);
        rvDetailAdapter = new CommonAdapter<SystemCityTreeVo>(getContext(), R.layout.item_region_category_detail, rvDetailList) {
            @Override
            protected void convert(ViewHolder holder, SystemCityTreeVo systemCityTreeVo, int position) {
                TextView tvCity = holder.getView(R.id.tvCity);
                ImageView avatar = holder.getView(R.id.avatar);
                TextView tvTitle = holder.getView(R.id.tvTitle);
                FlowTagLayout flowTagLayout = holder.getView(R.id.flowlayout_multi_select);
                //
                tvCity.setText(systemCityTreeVo.getName());
                //
                if (null != systemCityTreeVo.getChild() && !systemCityTreeVo.getChild().isEmpty()) {
                    flowTagLayout.setTag(systemCityTreeVo.getId());
                    FlowTagSimpleAdapter<SystemCityTreeVo> tagAdapter = new FlowTagSimpleAdapter<SystemCityTreeVo>(flowTagLayout.getContext());
                    flowTagLayout.setAdapter(tagAdapter);
                    flowTagLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_MULTI);//可多选
                    for (SystemCityTreeVo vo : systemCityTreeVo.getChild()) {
                        tagAdapter.addTag(vo);
                    }
                    flowTagLayout.setOnTagSelectListener(new FlowTagLayout.OnTagSelectListener() {
                        @Override
                        public void onItemSelect(FlowTagLayout flowTagLayout, int i, List<Integer> list) {
                            new RightTagSelectListener().onItemSelect(flowTagLayout, i, list);
                        }
                    });
                } else {
                    flowTagLayout.clearTags();
                }
            }
        };
        rvDetailAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                rvDetailCheckedPosition = i;
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
        rvDetail.setAdapter(rvDetailAdapter);

        //

        //初始化tagViewLayout
        mTagContainerLayout = findViewById(R.id.tagcontainerLayout);
        mTagContainerLayout.setCrossColor(getResources().getColor(R.color.black30));
        mTagContainerLayout.setOnTagClickListener(new TagView.OnTagClickListener() {

            @Override
            public void onTagClick(int position, String text) {
                tip("" + position);
            }

            @Override
            public void onTagLongClick(int position, String text) {

            }

            @Override
            public void onSelectedTagDrag(int position, String text) {

            }

            @Override
            public void onTagCrossClick(int position) {
                //tip(""+position);
                if (position < mTagContainerLayout.getChildCount()) {
                    String tagText = mTagContainerLayout.getTagText(position);
                    mTagContainerLayout.removeTag(position);
                    Log.i("TAG", tagText);
                    tagLayoutTags.remove(tagText);
                    selectedJobList.removeIf(item -> item.getName().equals(tagText));
                    //

                    FlowTagLayout flowTagLayout = flowTagLayoutMap.get(tagText);
                    List<Integer> postSelectedIndex = new ArrayList<>();
                    if (null != flowTagLayout) {
                        List<Integer> selectedIndexList = flowTagLayout.getSelectedIndexs();
                        for (int index : selectedIndexList) {
                            SystemCityTreeVo attrTreeVo = (SystemCityTreeVo) flowTagLayout.getAdapter().getItem(index);
                            if (!attrTreeVo.getName().equals(tagText)) {
                                postSelectedIndex.add(index);
                            }
                        }

                        if (!postSelectedIndex.isEmpty()) {
                            flowTagLayout.setSelectedPositions(postSelectedIndex);
                        } else {
                            flowTagLayout.clearSelection();
                        }
                    }
                }
                if (mTagContainerLayout.getChildCount() <= 0) {
                    binding.flKindShow.setVisibility(View.GONE);
                    binding.btnClearOptions.setEnabled(false);
                }
                binding.tvSelectedCountTip.setText("已选择" + mTagContainerLayout.getChildCount() + "/" + resultSize);
            }
        });

        //
        getCityCategoryTree();
    }

    @Override
    public void onClick(View view) {

    }

    class LeftRvListener implements RvListener {

        @Override
        public void onItemClick(int id, int position) {
            //PopTip.show("这是一个提示").showShort();
            isMoved = true;
            targetPosition = position;

            //刷新分类列表数据为当前一点击的右侧一级分类的二级子类
            leftCategoryBean = rvSortList.get(position);
            rvDetailList.clear();
            rvDetailList.addAll(leftCategoryBean.getChild());
            setChecked(position, true);
            //取消加入titile 否则二级分类索引会乱，或者SortBean的二级分类三级分类都加上code
            XUtil.runOnUiThread(new Runnable() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void run() {
                    rvDetailAdapter.notifyDataSetChanged();
                }
            });

        }
    }

    private void setChecked(int position, boolean isLeft) {
        Log.d(TAG + "-------->p", String.valueOf(position));
        if (isLeft) {
            rvSortCheckedPosition = position;
            //此处的位置需要根据每个分类的集合来进行计算
            int count = 0;
            for (int i = 0; i < position; i++) {
                count += leftCategoryBean.getChild().size();
            }
            count += position;
            //mSortDetailFragment.setData(count);
            //ItemHeaderDecoration.setCurrentTag(String.valueOf(targetPosition));//凡是点击左边，将左边点击的位置作为当前的tag
        } else {
            if (isMoved) {
                isMoved = false;
            }
            rvDetailCheckedPosition = position;
            //ItemHeaderDecoration.setCurrentTag(String.valueOf(position));//如果是滑动右边联动左边，则按照右边传过来的位置作为tag

        }
        //moveToCenter(position);

    }


    /**
     * 右侧工种列表，叶子工种tag点击事件处理
     */
    class RightTagSelectListener implements TagSelectListener {
        /**
         * @param flowTagLayout tagLayout组件
         * @param i             点击的第几个tag （tag索引） 对应tagAdapter的列表数据的索引
         * @param selectedList  点就后(包含当前点击的tag)tag选中的id列表
         */
        @Override
        public void onItemSelect(FlowTagLayout flowTagLayout, int i, List<Integer> selectedList) {

            SystemCityTreeVo thatTagTreeVo = (SystemCityTreeVo) flowTagLayout.getAdapter().getItem(i);
            if (selectedList.contains(i)) {
                //flowTagLayout的第i个tag被选中
                //Toaster.show("选中:"+thatTagTreeVo.getName());
                if (tagLayoutTags.size() >= resultSize) {
                    Toaster.show("最多可以选择" + resultSize + "个城市");
                    return;
                }
                if (tagLayoutTags.contains(thatTagTreeVo.getName())) {
                    Toaster.show("该工种已选择");
                } else {
                    tagLayoutTags.add(thatTagTreeVo.getName());
                    selectedJobList.add(thatTagTreeVo);
                    //
                    flowTagLayoutMap.put(thatTagTreeVo.getName(), flowTagLayout);
                }

            } else {
                //取消flowTagLayout的第i个tag
                //Toaster.show("取消:"+thatTagTreeVo.getName());
                tagLayoutTags.removeIf(item -> item.equals(thatTagTreeVo.getName()));
                selectedJobList.removeIf(item -> item.getName().equals(thatTagTreeVo.getName()));
                //
                flowTagLayoutMap.remove(thatTagTreeVo.getName());
            }
            mTagContainerLayout.setTags(tagLayoutTags);
            if (mTagContainerLayout.getChildCount() > 0) {
                binding.flKindShow.setVisibility(View.VISIBLE);
                binding.btnClearOptions.setEnabled(true);
            } else {
                binding.flKindShow.setVisibility(View.GONE);
                binding.btnClearOptions.setEnabled(false);
            }
            binding.tvSelectedCountTip.setText("已选择" + mTagContainerLayout.getChildCount() + "/" + resultSize);
        }
    }

    @SuppressLint("CheckResult")
    private void getCityCategoryTree() {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IOther.class)
                .listCityTree()
                .subscribeWith(new NoTipRequestSubscriber<List<SystemCityTreeVo>>() {

                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    protected void onSuccess(List<SystemCityTreeVo> jobCategoryTreeVoList) {
                        Log.i(TAG, "-------------获取城市列表树------------------");
                        Log.i(TAG, "-------------" + JsonUtil.toJson(jobCategoryTreeVoList) + "------------------");
                        Toaster.show("数据加载成功");
                        XUtil.runOnUiThread(() -> {
                            rvSortList.clear();
                            rvSortList.addAll(jobCategoryTreeVoList);
                            rvSortAdapter.notifyDataSetChanged();
                            rvDetailList.clear();
                            rvDetailList.addAll(jobCategoryTreeVoList.get(0).getChild());
                            rvDetailAdapter.notifyDataSetChanged();
                        });
                        appLoadingDialog.dismiss();
                        Log.i(TAG, "-------------获取城市列表树------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ;
                        ToastUtils.toast(e.getDisplayMessage());
                        Log.i(TAG, "-------------获取城市列表树-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                        appLoadingDialog.dismiss();
                    }

                });
    }
}